<template>
  <a-select v-model="selectValue" @change="change">
    <a-select-option v-for="(item, i) in data" :key="i" :value="item[`${itemKey}`]">{{ item[`${label}`] }}</a-select-option>
  </a-select>
</template>
<script>
const ENUM = 'enum'
const DIC = 'dic'
import { queryEnumerationValuesByName } from '@/api/base/enumeration.js'
import { dicList } from '@/api/base/dic.js'
export default {
  props: {
    // 下拉数据类型默认为枚举，可选值：enum：枚举,dic：字典
    type: {
      type: String,
      default: () => {
        return 'enum'
      },
    },
    // 枚举名称或字典名称
    name: {
      type: String,
      default: '',
    },
    // 下拉列表的value值属性名
    itemKey: {
      type: String,
      default: () => {
          return 'id'
      },
    },
    // 下拉列表的文本内容属性名
    label: {
      type: String,
      default: () =>{
          return 'name'
      },
    },
    // 是否显示全部
    all: {
      type: Boolean,
      default: false,
    },
    // 绑定值
    value: {
      type: [String, Number],
      default: '',
    },
    // 流程定义是否显示公开
    isOpen: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      data: [],
      selectValue: this.value,
    }
  },
  created() {
    this.data.length = 0
    if (this.all) {
        const allopt = {}
        allopt[`${this.itemKey}`] = ''
        allopt[`${this.label}`] = this.isOpen  ? '公开' : '全部'
        this.data.push(allopt)
    }
    if (!this.name) {
        return
    }
    if (this.type === ENUM) { // 枚举下拉
        queryEnumerationValuesByName({ enName: this.name}).then(res => {
            if (res.code === 0) {
                let enums = res.data
                enums.forEach(item => {
                    const enu = {}
                    enu[`${this.itemKey}`] = item[`${this.itemKey}`]
                    enu[`${this.label}`] = item[`${this.label}`]
                    this.data.push(enu)
                });
            }
        }).finally(() => {
          this.$emit("getSelectData", this.data)
        })
    } else if (this.type === DIC) { // 字典下拉
        dicList({ className: this.name }).then(res =>{
            if (res.code === 0) {
                let dics = res.data
                dics.forEach(item => {
                    const dic = {}
                    dic[`${this.itemKey}`] = item[`${this.itemKey}`]
                    dic[`${this.label}`] = item[`${this.label}`]
                    this.data.push(dic)
                });
            }
        })
    }
  },
  watch: {
      value (newVal) {
          this.selectValue = newVal
      },
      selectValue (newVal, oldVal) {
          if (newVal !== oldVal) {
              this.$emit("input", this.selectValue)
          }
      }
  },
  methods: {
    change() {
      this.$emit('change')
    },
  },
}
</script>
<style lang="less" scoped>
</style>